const { app, BrowserWindow } = require('electron');
const path = require('path');
const { exec, spawn } = require('child_process');
const createWindow = () => {
    const win = new BrowserWindow({
        width: 800,
        height: 600,
    });

    win.loadFile('index.html');
    // 5秒后启动程序
    setTimeout(startXuebi, 5000);
    console.log('shun77', process.env.NODE_ENV);
};
// 启动xuebi.exe
function startXuebi() {
    let exePath = path.join(process.resourcesPath, 'xuebi.exe');
    if (!app.isPackaged) {
        // 开发环境
        exePath = path.join(app.getAppPath(), 'resources/xuebi.exe');
    }
    console.log(`shun1: ${exePath}`);

    // 使用spawn而不是exec，以便我们可以获得进程对象用于后续关闭
    xuebiProcess = spawn(exePath, [], {
        detached: false, // 设置为false以便我们可以控制子进程
        stdio: 'ignore', // 忽略子进程的输入输出
    });

    xuebiProcess.on('error', (err) => {
        console.error('shun2:', err);
        xuebiProcess = null;
    });

    xuebiProcess.on('exit', (code, signal) => {
        console.log(`shun3: ${code}, shun4: ${signal}`);
        xuebiProcess = null;
    });

    console.log('shun5');

    // 5秒后关闭程序
    setTimeout(stopXuebi, 5000);
}
// 关闭xuebi.exe
function stopXuebi() {
    if (!xuebiProcess) {
        console.log('shun6');
        return;
    }

    console.log('准备关闭xuebi.exe');

    // Windows平台使用taskkill更可靠
    if (process.platform === 'win32') {
        exec(`taskkill /pid ${xuebiProcess.pid} /f`, (err) => {
            if (err) {
                console.error('shun7:', err);
            } else {
                console.log('shun8');
                xuebiProcess = null;
            }
        });
    } else {
        // 非Windows平台
        xuebiProcess.kill();
        console.log('已发送终止信号给xuebi.exe');
        xuebiProcess = null;
    }
}

app.whenReady().then(() => {
    createWindow();
});
